import './widgets.less'

export default (app) => {
  app.component('NoData', {
    template: `
      <div class="no-data">
        <SmartLoading v-if="isLoading"></SmartLoading>
        <strong v-else>暂无数据</strong>
      </div>
    `,
    props: ['isLoading']
  })

  app.component('SmartLoading', {
    template: `
      <div class="smart-loading">
        <ul>
          <li
            v-for="(n, idx) in len"
            :key="idx"
            :style="{
              transform: 'rotate(' + (idx / len * 360) + 'deg) translateX(180%)',
              backgroundColor: 'hsla(0, 0%, ' + (1 - (idx / (len - 1) * (1 - offset * 2) + offset)) * 100 + '%, 1)'
            }"
          ></li>
        </ul>
      </div>
    `,
    data() {
      return {
        len: 12,
        offset: 0,
      }
    }
  })

  app.component('SmartToolTip', {
    template: `
      <el-tooltip placement="top"
        v-if="content?.length > maxLen"
        :show-after="300"
      >
        <template #content>
          <pre>{{ content_ }}</pre>
        </template>
        <span>{{ $root.substr(content, maxLen) }}</span>
      </el-tooltip>
      <template v-else>{{ content }}</template>
    `,
    props: {
      content: {
        type: [String, null],
        default: '',
      },
      maxLen: {
        type: Number,
        default: 60,
      },
      isJson: {
        type: Boolean,
        default: false,
      }
    },
    computed: {
      content_() {
        const content = this.content || ''

        if (this.isJson) {
          try {
            return JSON.stringify(JSON.parse(content), 0, 2)
          } catch (e) {
            console.log(e, 'content is not json', content)
          }
        }

        return content
      }
    }
  })

  app.component('OpenFile', {
    template: `
      <button v-if="$root.is.local" @click="openFile" class="btn btn-sm btn-success">打开组件</button>
    `,
    props: ['path'],
    methods: {
      openFile() {
        const path = this.path || this.$parent.$options.__file
        fetch('/__open-in-editor?file=' + encodeURIComponent(path))
      }
    }
  })
}